/**************************************************
获取分数-绩效合同
* */
<template>
  <div class="mod-config">
    <basic-container>
      <div>
          <div style="display: flex;margin-bottom: 10px">
            <div class="input-box" v-if="tabType == '0'">
              <span class="label">员工编号：</span>
              <el-input v-model="searchForm.ygbm" placeholder="请输入员工编号" clearable ></el-input>
            </div>
            <div class="input-box" v-if="tabType == '1'">
              <span class="label">机构编号：</span>
              <el-input v-model="searchForm.deptCode" placeholder="请输入机构编号" clearable ></el-input>
            </div>
            <el-button
              icon="el-icon-search"
              class="marginLeft"
              type="primary"
              @click="getDataList()"
            >检索</el-button>
          </div>
            <el-form
              :model="searchForm"
              @keyup.enter.native="getDataList()"
              label-width="100px"
              class="form-inline">
              <el-form-item label="分数个数：" v-if="imported=='0'?true:false">
                <template v-if="scoreNumList.length>0">
                 <el-checkbox :indeterminate="isIndeterminateNum" v-model="checkAllNum" @change="checkAllNumChange" class="fla">全选</el-checkbox>
                 <el-checkbox-group v-model="scoreNum" @change="scoreNumChange">
                   <el-checkbox  :key="item.renderIndex" :label="item.scorecount" v-for="item in scoreNumList">{{ item.scorecount}}个</el-checkbox>
                 </el-checkbox-group>
                </template>
                <template v-else>
                  无
                </template>
              </el-form-item>

              <el-form-item label="所属部门：">
                <template v-if="bmsArr.length>0">
                    <el-checkbox :indeterminate="isIndeterminateBm" v-model="checkAllBm"
                                 @change="handleCheckAllBmChange" class="fla">全选</el-checkbox>
                    <el-checkbox-group v-model="bms" @change="bmsChange" class="fla">
                      <el-checkbox v-for="item in bmsArr" :label="item.dept_name" :key="item.dept_id">{{item.dept_name}}</el-checkbox>
                    </el-checkbox-group>
                </template>
                <template v-else>
                  无
                </template>
              </el-form-item>

              <el-form-item label="岗位名称：" v-if="tabType == '0'">
                <template v-if="gwArr.length>0">
                    <el-checkbox :indeterminate="isIndeterminateGw" v-model="checkAllGw" @change="checkAllGwChange" class="fla">全选</el-checkbox>
                    <el-checkbox-group v-model="gwmc" @change="gwidChange" >
                        <el-checkbox :key="item.gwmc" :label="item.gwmc"  v-for="item in gwArr">{{item.gwmc}}</el-checkbox>
                    </el-checkbox-group>
                </template>
                <template v-else>
                  无
                </template>
              </el-form-item>
            </el-form>
        <div class="boxContain" style="justify-content: flex-end" >
          <el-button type="primary" plain @click="exportXlsx">模板下载</el-button>
          <el-button type="primary" plain size="small" @click="openImport()">导入数据</el-button>
          <el-button type="primary" plain @click="closeDialog" >返回</el-button>
        </div>
        <el-form style="margin-top: 20px" :inline="true">
            <el-form-item label="通用公式" style="float: right"  v-if="imported=='0'?true:false">
              <el-select v-model="generalFormulaId" value-key="id" clearable placeholder="请选择公式" @change="generalFormulaChange">
                <el-option
                  v-for="item in formulaOptions"
                  :key="item.id"
                  :label="item.gsMc"
                  :value="item.id">
                </el-option>
              </el-select>
              <el-button
                type="primary"
                plain
                class="marginLeft"
                @click="calAllScore"
              >计算</el-button>
<!--              <el-button type="primary" plain @click="generateScore">生成得分</el-button>-->
            </el-form-item>
        </el-form>

        <!--数据列表-->
        <el-table
          style="width: 100%;margin-top:20px"
          :data="dataList"
          border
          header-align="center"
          v-loading="dataListLoading"
          v-if="rednermsg"
          @row-click="unfoldBtn"
          @selection-change="handleSelectionChange">
        >
          <!--<el-table-column type="selection" width="55" align="center"></el-table-column>-->
          <el-table-column type="index" width="55" align="center" label="序号"></el-table-column>
          <el-table-column prop="ygbm" align="center"  label="员工编号" v-if="tabType == '0'"></el-table-column>
          <el-table-column prop="ygname" align="center"  label="姓名"  v-if="tabType == '0'"></el-table-column>
          <el-table-column prop="deptName" align="center"  label="部门" ></el-table-column>
          <el-table-column prop="gwmc" align="center"  label="岗位" v-if="tabType == '0'"></el-table-column>
          <el-table-column prop="score" align="center"  label="分数" v-if="imported=='0'?true:false">
            <template slot-scope="scope">
              <div v-if="scope.row.rowshows == false">
                  <span v-for="item in scope.row.score && scope.row.score.split(',')">
                     {{ item }}<br/>
                  </span>
              </div>
              <div v-if="scope.row.rowshows == true"
                   v-for="(item, index) in cutout(scope.row.score) && cutout(scope.row.score).slice( 0, 2 )" :key="index">
                <el-badge
                  :value="cutout(scope.row.score).length"
                  :max="9"
                  v-if=" cutout(scope.row.score).length > 2 && index === 0" class="itembadge">
                  <span style="padding-right: 0px">{{ item }} </span>
                </el-badge>
                <span v-else>{{ item }}</span>
              </div>
            </template>

          </el-table-column>
          <el-table-column prop="gsid" align="center"  label="公式"  v-if="imported=='0'?true:false">
            <template slot-scope="scope">
              <el-select v-model="scope.row.gsid" value-key="id" placeholder="请选择公式"
                  @change="calRowScore(scope.row, scope.$index)">
                <el-option
                  v-for="item in scope.row.formulaOptions"
                  :key="item.id"
                  :label="item.gsMc"
                  :value="item.id">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="sumScore" align="center"  label="总分"></el-table-column>
          <el-table-column  align="center"  label="操作" v-if="imported=='0'?true:false">
             <template slot-scope="scope">
                  <el-button  type="primary" plain @click.stop="showDetail(scope.row)">查看</el-button>
             </template>
          </el-table-column>
        </el-table>

      </div>
      <div style="margin-top: 20px;display: flex;justify-content: flex-end">
        <!-- <el-button type="primary" plain @click="generateScore">生成得分</el-button>
        <el-button type="primary" @click="saveAllScore">保存</el-button>-->
      </div>

      <scoreMxView v-if="scoreMxViewShow" ref="scoreMxView" ></scoreMxView>

      <!--导入-->
      <el-dialog width="40%" title="导入" :visible.sync="innerVisible" append-to-body>
        <el-row class="mb10" style="height: 10vh;" :gutter="10">
          <el-col :span="4">
            <el-upload
              style="margin-left: 8px;"
              class="upload-demo"
              action
              :on-change="handleChange"
              :show-file-list="false"
              :on-remove="handleRemove"
              :file-list="fileListUpload"
              :limit="limitUpload"
              accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
              :auto-upload="false"
            >
              <el-button type="primary" plain class="fr">导入</el-button>
            </el-upload>
          </el-col>
        </el-row>
      </el-dialog>

    </basic-container>
  </div>
</template>

<script>
    // 接口 api
    import {
        scoreExportExcel,
        fractionMxList,
        calAllScoreByIds,
        calRowScoreById,
        subAllScore,
        getGwListById,
        getScoreListById,
        getSysDeptDtoList,
        getFormulaList,
        generateScoreById,
        importPfData
    } from "@/api/statisticsanalysis/fractionGet.js";
    import scoreMxView from "./scoreMxView";
    import { mapGetters} from "vuex";
    import store from "@/store";
    export default {
        data(){
            return {
                headers: {
                    Authorization: "Bearer " + store.getters.access_token
                },
                searchForm: {ygbm:'',lx:''}, //查询表单
                multipleSelection: [], //表格中被选中的数据
                dataList: [],
                dataListLoading: false,
                menuType:'',
                id:'', //提取列表 id
                formulaOptions: [],
                checkAllGw:false,
                checkAllNum:false,
                checkAllBm:false,
                isIndeterminateGw: false,
                isIndeterminateNum: false,
                isIndeterminateBm: false, // 全选框是否在勾选状态
                scoreNumList:[], //分数个数列表
                scoreNum:[],
                gwArr:[], //岗位列表
                gwmc:[],
                bmsArr: [], //部门列表
                bms: [], // 初始选中的值
                generalFormulaId: '' ,//总的公式id
                rednermsg: true,
                scoreMxViewShow:false,
                innerVisible:false,
                limitUpload: 3,
                fileListUpload: [],
                accountList: [],
                imported:'0' ,//  0 数据提取 1 导入数据
                tabType : '0'
            };
        },
        components: {
            scoreMxView
        },
        filters: {},
        computed: {
            ...mapGetters(["permissions"])
        },
        watch: {
              // gwid(newval,oldval) {
              //     this.gwid = newval ;
              //     this.getDataList() ;
              // }
        },
        created() {
        },
        methods: {
            init(id,menuType,tabType){
                this.id = id ;
                this.menuType = menuType ;
                this.tabType = tabType || '0' ;//0 人员 1机构
                this.getGwList(id) ; //获取岗位列表
                this.getScoreList(id) ; //获取f分数个数列表
                this.getFormulaList() ;//获取公式列表
                this.getDeptDtoList(id) ;//获取部门名称列表
            },
            // 勾选数据
            handleSelectionChange(val) {
                if (val.length == 0) {
                    this.canDelete = true;
                } else{
                    this.canDelete = false ;
                }
                this.multipleSelection = val;
            },
            // 获取数据列表
            getDataList() {
                    // 获取数据列表
                    this.dataListLoading = true;
                    this.searchForm.lx = this.menuType ;
                    this.searchForm.sftqid = this.id ;
                    this.searchForm.gwmc = this.gwmc.toString() ;
                    this.searchForm.deptName = this.bms.toString() ;
                    this.searchForm.scorecount = this.scoreNum.toString() ;
                    this.searchForm.type = this.tabType ;
                    fractionMxList(
                            Object.assign(
                                {
                                    current: 1,
                                    size: 10000,
                                },
                                this.searchForm
                            )
                        )
                        .then(r => {
                                if (r.data.code == 0) {
                                    this.dataListLoading = false ;
                                    this.dataList = r.data.data.records ;
                                    this.dataList.map(it=>{
                                        it.formulaOptions = this.formulaOptions ;
                                        it.rowshows = true;
                                    });

                                    if (this.dataList.length>0 ){
                                        this.imported = this.dataList[0].imported  ;
                                    }

                                }
                            })
                        .catch(err => {});
            },
            //刷新界面
            refreshDataList(){
                this.getDataList() ;
            },
            // 关闭弹窗
            closeDialog() {
                this.$emit('closeDialog') ;
            },
            //通用公式计算分数
            calAllScore(){
              if (!this.scoreNum){
                  this.$message.error("请选择分数个数");
                  return  ;
              }
                if (this.scoreNum && this.scoreNum.length>1){
                    this.$message.error("分数个数只允许选择一个");
                    return  ;
                }
               if ( !this.generalFormulaId) {
                   this.$message.error("请选择公式");
                   return  ;
               }
              let ids =  this.dataList.map(it=>{
                    return it.id ;
              })

              calAllScoreByIds({ids:ids.toString(),gsId:this.generalFormulaId,type:this.tabType}).then(r => {
                if (r.data.code == 0) {
                    this.$message.success("计算成功");
                    this.getDataList();
                } else {
                    this.$message.warning(r.data.msg);
                }
              }).catch(() => {

              });

            },
            //计算单人得分
            calRowScore(row){

                calRowScoreById(row.id,row.gsid).then(r => {
                    if (r.data.code == 0) {
                       this.$message.success("计算分数成功");
                       this.getDataList();
                    } else {
                        this.$message.warning(r.data.msg);
                    }
                }).catch(() => {

                });
            },
            //保存总分
            saveAllScore(){
                subAllScore({
                    // articles: this.articlesAdd,
                    // mediaId: this.articlesMediaId,
                    // appId: this.checkAppId
                }).then(response => {

                }).catch(() => {

                })
            },
            //通过提取分数id获取岗位列表
            getGwList(id){
                getGwListById(id).then(r => {
                    if (r.data.code == 0) {
                         this.gwArr= r.data.data ;
                    } else {
                        this.$message.warning(r.data.msg);
                    }
                }).catch(() => {

                });
            },
            //获取部门名称列表
            getDeptDtoList(id){
                this.bmsArr = [];
                getSysDeptDtoList(id).then(res => {
                    this.bmsArr =  res.data.data ;
                });
            },
        //通过提取分数id获取分数个数列表
            getScoreList(id){
                getScoreListById(id).then(r => {
                    if (r.data.code == 0) {
                        this.scoreNumList= r.data.data ;
                        let i = 0;
                        this.scoreNumList.map(it=>{
                            it.renderIndex = i++ ;
                        });

                    } else {
                        this.$message.warning(r.data.msg);
                    }
                }).catch(() => {

                });
            },
            //获取公式列表
            getFormulaList(){
                getFormulaList().then(r => {
                    if (r.data.code == 0) {
                        this.formulaOptions= r.data.data.records ;
                        this.getDataList();
                    } else {
                        this.$message.warning(r.data.msg);
                    }
                }).catch(() => {

                });
            },
            generalFormulaChange(){ //所有数据 公式重新赋值
                // this.dataList.map(it=>{
                //     this.$set(it, 'gsid',this.generalFormulaId );
                // })
            },
            scoreNumChange(value){
                let checkedCount = value.length;
                this.checkAllNum = checkedCount === this.scoreNumList.length;
                this.isIndeterminateNum = checkedCount > 0 && checkedCount < this.scoreNumList.length;
                this.getDataList() ;
            },
            checkAllNumChange(val) {
                let scores = this.scoreNumList.map(it=>{
                    return it.scorecount ;
                })
                this.scoreNum = val ? scores : [];
                this.isIndeterminateNum = false ;
                this.getDataList() ;
            },
            gwidChange(value){
                let checkedCount = value.length;
                this.checkAllGw = checkedCount === this.gwArr.length;
                this.isIndeterminateGw = checkedCount > 0 && checkedCount < this.gwArr.length;
                this.getDataList() ;
            },
            checkAllGwChange(val) {

                let gws = this.gwArr.map(it=>{
                    return it.gwmc ;
                })
                this.gwmc = val ? gws : [];
                this.isIndeterminateGw = false ;
                this.getDataList() ;
            } ,

            bmsChange(value) {
                let checkedCount = value.length;
                this.checkAllBm = checkedCount === this.bmsArr.length;
                this.isIndeterminateBm = checkedCount > 0 && checkedCount < this.bmsArr.length;
                this.getDataList() ;
            },
            handleCheckAllBmChange(val) {
                let bms = this.bmsArr.map(it=>{
                    return it.dept_name ;
                })
                this.bms = val ? bms : [];
                this.isIndeterminateBm = false ;
                this.getDataList() ;
            },
            generateScore(){
                generateScoreById(this.id).then(r => {
                    if (r.data.code == 0) {
                        this.$message.success("得分已生成");
                    } else {
                        this.$message.warning(r.data.msg);
                    }
                }).catch(() => {

                });
            },
            //row折叠、展开
            unfoldBtn(row) {
                row.rowshows = !row.rowshows;
                this.rednermsg = false;
                this.$nextTick(() => {
                    this.rednermsg = true;
                });
            },
            //拆分数据
            cutout(cellValue) {
                if (cellValue) {
                    let c = cellValue.split(",");
                    if (c.size < 1) {
                        c.push("-");
                        c.push("-");
                    } else if (c.size < 2) {
                        c.push("-");
                    }
                    return c;
                }
            },
            //查看详情
            showDetail(rowData){
              this.scoreMxViewShow = true  ;
              this.$nextTick(it=>{
                  this.$refs.scoreMxView.init(rowData,this.tabType) ;
              })
            },
            openImport() {
                this.sftqId = this.id ;
                this.innerVisible = true;
            },
            // excel表上传
            handleChange(file, fileList) {
                this.fileTemp = file.raw;
                let fileName = file.raw.name;
                let fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
                // 判断上传文件格式
                if (this.fileTemp) {
                    if (fileType == "xlsx" || fileType == "xls") {
                        this.importf(this.fileTemp);
                        this.innerVisible = false;

                    } else {
                        this.$message({
                            type: "warning",
                            message: "附件格式错误，请删除后重新上传！"
                        });
                    }
                } else {
                    this.$message({
                        type: "warning",
                        message: "请上传附件！"
                    });
                }
            },
            //导入的方法
            importf(obj) {
                this.dialogVisible = true;
                var _this = this;
                let inputDOM = this.$refs.inputer; // 通过DOM取文件数据
                this.file = event.currentTarget.files[0];
                let rABS = false; //是否将文件读取为二进制字符串
                let f = this.file;
                let reader = new FileReader();
                //if (!FileReader.prototype.readAsBinaryString) {
                FileReader.prototype.readAsBinaryString = function(f) {
                    let binary = "";
                    let rABS = false; //是否将文件读取为二进制字符串
                    let pt = this;
                    let wb; //读取完成的数据
                    let outdata;
                    let reader = new FileReader();
                    reader.onload = function(e) {
                        let bytes = new Uint8Array(reader.result);
                        let length = bytes.byteLength;
                        for (let i = 0; i < length; i++) {
                            binary += String.fromCharCode(bytes[i]);
                        }
                        let XLSX = require("xlsx");
                        if (rABS) {
                            wb = XLSX.read(btoa(fixdata(binary)), {
                                //手动转化
                                type: "base64"
                            });
                        } else {
                            wb = XLSX.read(binary, {
                                type: "binary"
                            });
                        }
                        // outdata就是你想要的东西 excel导入的数据
                        outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);

                        let result = outdata.map(item => {
                            return { ygbm: item.__EMPTY, ygname:item.__EMPTY_1,sumScore: item.__EMPTY_2}
                        } ) ;
                        result.shift() ; //删除数组第一行数据

                        //验证sumScore为正数保留两位小数
                        let flag = result.every(it=>{
                            return typeof(it.sumScore) == "number" ;
                        }) ;

                        if (!flag){
                            _this.$message.error('导入失败，总分为两位小数的正数');
                            return ;
                        }

                        // excel 数据再处理
                        // let arr = [];
                        // outdata.map(v => {
                        //     // let jsonString = JSON.stringify(v).replace(/\*/g, '').replace(/\s/ig,'');
                        //     let jsonString = JSON.stringify(v).replace(/\//g, "").replace(/\s/gi, "");
                        //     v = JSON.parse(jsonString);
                        //     let obj = {};
                        //     obj.ygbm = v.员工编号;
                        //     obj.ygname = v.姓名;
                        //     obj.sumScore = v.总分;
                        //     arr.push(obj);
                        // });
                        // _this.accountList = [...arr];

                        importPfData(result,_this.sftqId).then(r => {
                            console.log(r);
                            if(r.data.data.length != 0){
                                let data = r.data.data;
                                _this.$message.success("导入成功");
                               _this.init(_this.id,_this.menuType);
                            }else{
                                _this.$message.error("导入失败");
                            }

                        }).catch(error => {
                            console.log(error);
                        });
                    };
                    reader.readAsArrayBuffer(f);
                };
                if (rABS) {
                    reader.readAsArrayBuffer(f);
                } else {
                    reader.readAsBinaryString(f);
                }
            },
            //模板下载
            exportXlsx() {
                this.$message.closeAll();
                this.$message.success("下载成功!");
                window.location.href = "../../static/"+this.menuType+"-score.xlsx";
            },
            // 移除excel表
            handleRemove(file, fileList) {
                this.fileTemp = null;
            },
        }
    };
</script>

<style lang="scss" scoped>
 .boxContain{padding-bottom: 10px;border-bottom:1px solid rgb(176, 189, 226);display: flex;justify-content:flex-end!important;width: 100%}
  .floatRight{float: right}
 .fla {float: left;margin-right: 15px !important;margin-left: 5px;}
  /deep/.el-badge__content.is-fixed{right: 0px!important;}
  .input-box{width: 25%}
  .input-box .label{width: 100px;display: inline-block;line-height: 35px;padding-right: 10px;text-align: right}
  .input-box .el-input{width: calc(100% - 100px) !important}
</style>
